const mongoose = require("mongoose");
mongoose.connect("mongodb://localhost:27017/bilibili");

// once 事件回调函数只执行一次
mongoose.connection.once("connected", () => {
  // 设置集合中文档的属性以及属性的值
  let BookSchema = new mongoose.Schema({
    // name: String,
    // author: String,
    // price: Number,
    name: {
      type: String,
      required: [true, "Name is required"],
      minlength: [2, "Name must be at least 2 characters"],
      maxlength: [50, "Name cannot exceed 50 characters"],
      unique: true, // 表面该属性必须唯一
    },
    price: {
      type: Number,
      min: [0, "Price must be at least 0"],
      max: [120, "Price cannot exceed 120"],
      required: true, // 表面该属性必须不为空
    },
    email: {
      type: String,
      match: [
        /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/,
        "Please fill a valid email address",
      ],
    },
    status: {
      type: String,
      enum: ["active", "inactive", "pending"], // 枚举类型 限制取值。设置的值必须是数组中的一个
      default: "pending", // 默认值
    },
  });

  // 创建模型对象  对文档操作的封装对象
  let BookModal = mongoose.model("books", BookSchema);

  // 读取文档
  //   BookModal.findOne({ name: "zfpx" }, (err, res) => {
  //     if (err) {
  //       console.log(err);
  //       return;
  //     }
  //     console.log(res);
  //   });
  //   // 根据ID查询文档
  //   BookModal.findById("xxxxxxx", (err, res) => {
  //     if (err) {
  //       console.log(err);
  //       return;
  //     }
  //     console.log(res);
  //   });

  //   // 批量读取
  //   BookModal.find({ name: "zfpx" }, (err, res) => {
  //     if (err) {
  //       console.log(err);
  //       return;
  //     }
  //     console.log(res);
  //   });
  BookModal.find().then((res) => {
    console.log(res);
  });
});
